<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace App\Cola\Service;

use App\Cola\Mapper\ColaLedgerMapper;
use App\Cola\Model\ColaBill;
use App\Cola\Model\ColaLedger;
use Hyperf\DbConnection\Db;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;

/**
 * 账本服务类
 */
class ColaLedgerService extends AbstractService
{
    /**
     * @var ColaLedgerMapper
     */
    public $mapper;

    public function __construct(ColaLedgerMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    /**
     * 列表
     * */
    public function getApiList($params, $field = ['*'], $page = 1, $size = 20)
    {
        $query = ColaLedger::query()->select($field);
        if (!empty($params['status'])) {
            $query->where('status', $params['status']);
        }
        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }
        $count_query = clone $query;
        $list_query = clone $query;
        $count = $count_query->count();
        $list = $list_query->offset($page)->limit($size)->orderByDesc('weigh')->get();

        return ['count' => $count, 'list' => $list];
    }

    /**
     * 列表
     * */
    public function getApiDetail($params, $field = ['*'])
    {
        $query = ColaLedger::query()->select($field);
        if (!empty($params['id'])) {
            $query->where('id', $params['id']);
        }
        if (!empty($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }
        if (isset($params['is_default'])) {
            $query->where('is_default', $params['is_default']);
        }

        return $query->orderByDesc('weigh')->first();
    }


    /**
     * 新增/修改
     * */
    public function apiSave(array $params)
    {
        // 查找是否存在相同 title 的记录，排除当前记录（根据 id）
        $existingRecord = ColaLedger::where('title', $params['title'])
            ->where('id', '<>', $params['id'] ?? 0)
            ->first();

        // 如果找到相同 title 的记录，抛出异常
        if ($existingRecord) {
            throw new NormalStatusException('账单名称已存在');
        }

        // 查找现有记录，或者创建一个新的实例
        $model = ColaLedger::find($params['id']) ?? new ColaLedger();

        // 更新属性
        $model->user_id = $params['user_id'];
        $model->title = $params['title'];
        $model->img = $params['img'];
        $model->is_default = $params['is_default'];

        // 保存记录
        $model->save();

        return $model;
    }

    /**
     * 删除代码
     * */
    public function apiDel(array $params)
    {
        $model = ColaLedger::find($params['id']);

        if (!$model) {
            throw new NormalStatusException('账本不存在');
        }

        return $model->delete();
    }

    /**
     * 账单明细加入账单
     * */
    public function JoinBillService($user_id, $ledger_id, $bill_id)
    {
        // 查找账单和账本
        $bill = ColaBill::find($bill_id);
        $ledger = ColaLedger::find($ledger_id);

        if (!$bill) {
            throw new NormalStatusException("账单详情不存在");
        }

        if (!$ledger) {
            throw new NormalStatusException("账本不存在");
        }

        // 检查关联是否已存在
        $existingRelation = $ledger->bills()
            ->wherePivot('cola_bill_id', $bill_id)
            ->wherePivot('cola_user_id', $user_id)
            ->exists();

        if ($existingRelation) {
            throw new NormalStatusException("账单已经在该账本中存在了");
        }

        // 关联账单到账本，并指定用户
        $ledger->bills()->attach($bill->id, ['cola_user_id' => $user_id]);

        return true;
    }


}